/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.services;

import com.google.inject.Inject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.xptracker.domain.Domain;
import org.xptracker.domain.ScheduledTask;
import org.xptracker.persistence.RollbackException;

import java.io.IOException;
import java.io.StringReader;

public class JsJob implements Job {
  public static final String JOB_ID = "jobId";

  @Inject
  private Domain domain;

  @Inject
  private JsEngine jsEngine;

  private String jobId;

  public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    final Log log = LogFactory.getLog(getClass());
    if (StringUtils.isNotBlank(jobId)) {
      final ScheduledTask task = domain.loadEntity(ScheduledTask.class, jobId);
      jsEngine.withEngine(new EngineReceiver() {
        public void receive(Context cx, Scriptable scope) {
          try {
            log.debug("Executing scheduled task '" + task.getName() + "'");
            cx.evaluateReader(scope, new StringReader(task.getScript()), "<" + task.getName() + ">", 1, null);
          } catch (IOException e) {
            throw new RollbackException(e);
          }
        }
      });
    } else {
      log.error("No job ID specified for job.");
    }
  }

  public void setJobId(String jobId) {
    this.jobId = jobId;
  }
}
